from django.shortcuts import render
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.views import View
from datetime import datetime

# Create your views here.
@method_decorator(csrf_protect, name="dispatch")
@method_decorator(login_required, name="dispatch")
class UploadView(View):
    def post(self, request, *args, **kwargs):
        for file_key in ['file1', 'file2', 'file3', 'file4']:
            if file_key in request.FILES:
                return JsonResponse({"error": "文件未上传"}, status=400)

            uploaded_file = request.FILES[file_key]

            file_path = f"/uploads/{request.user.username}_{datetime.now().strftime("%Y%m%d%H%M%S")}_{uploaded_file.name}"
            with open(file_path, 'wb+') as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)

        return JsonResponse({'status': 'success', 'filename': uploaded_file.name}, status=200)

    def get(self, request, *args, **kwargs):
        return render(request, template_name="home.index")


def process_view(request):
    return render(request, "process1.html")


def prepare_view(request):
    return render(request, "prepare1.html")

# 20250908添加
@csrf_exempt
@require_http_methods(["POST"])
def create_or_update_monthly_record(request):
    """
    创建或更新月度记录
    查询标准：同时使用产品代码(code)和日期(yyyymm格式)
    """
    try:
        # 解析请求数据
        if request.content_type == 'application/json':
            data = json.loads(request.body)
        else:
            return JsonResponse({
                'success': False, 
                'error': '请使用JSON格式发送数据'
            }, status=400)
        
        # 获取必要参数
        code_str = data.get('code')
        date_str = data.get('date')  # yyyymm格式，如 202201
        
        if not code_str or not date_str:
            return JsonResponse({
                'success': False, 
                'error': '缺少必需参数: code 或 date'
            }, status=400)
        
        # 验证日期格式
        try:
            year = int(date_str[:4])
            month = int(date_str[4:6])
            if month < 1 or month > 12:
                raise ValueError("月份必须在1-12之间")
            # 创建日期对象 (格式: YYYY-MM-01)
            date_obj = datetime(year, month, 1).date()
        except (ValueError, IndexError) as e:
            return JsonResponse({
                'success': False, 
                'error': f'日期格式错误，请使用yyyymm格式，如202201。错误: {str(e)}'
            }, status=400)
        
        # 检查产品代码是否存在，如果不存在则创建
        product_code, code_created = ProductCode.objects.get_or_create(
            code=code_str,
            defaults={
                'name': data.get('product_name', f'产品-{code_str}'),
                'description': data.get('description', ''),
                'is_active': True
            }
        )
        
        # 获取其他数据
        production_quantity = data.get('production_quantity', 0)
        sales_quantity = data.get('sales_quantity', 0)
        unit_price = data.get('unit_price', 0)
        unit_cost = data.get('unit_cost', 0)
        unit_cost2 = data.get('unit_cost2', 0)
        
        # 验证数值类型
        try:
            production_quantity = Decimal(str(production_quantity))
            sales_quantity = Decimal(str(sales_quantity))
            unit_price = Decimal(str(unit_price)) if unit_price else Decimal('0')
            unit_cost = Decimal(str(unit_cost)) if unit_cost else Decimal('0')
            unit_cost2 = Decimal(str(unit_cost2)) if unit_cost2 else Decimal('0')
        except (InvalidOperation, ValueError) as e:
            return JsonResponse({
                'success': False, 
                'error': f'数值格式错误: {str(e)}'
            }, status=400)
        
        # 获取或创建价格记录
        price_obj = None
        if unit_price > 0:
            price_obj, price_created = Price.objects.get_or_create(
                code=product_code,
                month=date_obj,
                defaults={
                    'unit_price': unit_price
                }
            )
            # 如果价格记录已存在且价格不同，则更新
            if not price_created:
                if price_obj.unit_price != unit_price:
                    old_price = float(price_obj.unit_price)
                    price_obj.unit_price = unit_price
                    price_obj.save()
                else:
                    old_price = None
            else:
                old_price = None
        else:
            # 如果单价为0或空，查找是否已存在该月的价格记录
            try:
                price_obj = Price.objects.get(code=product_code, month=date_obj)
            except Price.DoesNotExist:
                price_obj = None
        
        # 获取或创建成本记录
        cost_obj = None
        if unit_cost > 0 or unit_cost2 > 0:
            cost_obj, cost_created = Cost.objects.get_or_create(
                code=product_code,
                month=date_obj,
                defaults={
                    'unit_cost': unit_cost,
                    'unit_cost2': unit_cost2
                }
            )
            # 如果成本记录已存在且成本不同，则更新
            if not cost_created:
                if cost_obj.unit_cost != unit_cost or cost_obj.unit_cost2 != unit_cost2:
                    old_cost = float(cost_obj.unit_cost)
                    old_cost2 = float(cost_obj.unit_cost2)
                    cost_obj.unit_cost = unit_cost
                    cost_obj.unit_cost2 = unit_cost2
                    cost_obj.save()
                else:
                    old_cost = None
                    old_cost2 = None
            else:
                old_cost = None
                old_cost2 = None
        else:
            # 如果成本为0或空，查找是否已存在该月的成本记录
            try:
                cost_obj = Cost.objects.get(code=product_code, month=date_obj)
            except Cost.DoesNotExist:
                cost_obj = None
        
        # 核心逻辑：根据code和date同时查询，存在则更新，不存在则创建
        try:
            # 同时使用code和date作为查询条件
            monthly_record = MonthlyRecord.objects.get(
                code=product_code,
                month=date_obj
            )
            
            # 记录更新前的数据
            old_data = {
                'production_quantity': float(monthly_record.production_quantity),
                'sales_quantity': float(monthly_record.sales_quantity),
                'price': float(monthly_record.price.unit_price) if monthly_record.price else 0,
                'cost': float(monthly_record.cost.unit_cost) if monthly_record.cost else 0,
                'cost2': float(monthly_record.cost.unit_cost2) if monthly_record.cost else 0,
                'total_sales_amount': float(monthly_record.total_sales_amount),
                'total_cost_amount': float(monthly_record.total_cost_amount),
                'profit': float(monthly_record.profit)
            }
            
            # 更新现有记录
            monthly_record.production_quantity = production_quantity
            monthly_record.sales_quantity = sales_quantity
            monthly_record.price = price_obj
            monthly_record.cost = cost_obj
            monthly_record.save()
            
            action = 'updated'
            message = f'记录已更新 - 产品代码: {code_str}, 日期: {date_str}'
            
            # 返回更新后的数据
            response_data = {
                'success': True,
                'action': action,
                'message': message,
                'old_data': old_data,
                'data': {
                    'code': product_code.code,
                    'date': date_str,
                    'production_quantity': float(production_quantity),
                    'sales_quantity': float(sales_quantity),
                    'unit_price': float(unit_price) if unit_price else 0,
                    'unit_cost': float(unit_cost) if unit_cost else 0,
                    'unit_cost2': float(unit_cost2) if unit_cost2 else 0,
                    'total_sales_amount': float(monthly_record.total_sales_amount),
                    'total_cost_amount': float(monthly_record.total_cost_amount),
                    'profit': float(monthly_record.profit)
                }
            }
            
        except MonthlyRecord.DoesNotExist:
            # 创建新记录
            monthly_record = MonthlyRecord.objects.create(
                code=product_code,
                month=date_obj,
                production_quantity=production_quantity,
                sales_quantity=sales_quantity,
                price=price_obj,
                cost=cost_obj
            )
            
            action = 'created'
            message = f'记录已创建 - 产品代码: {code_str}, 日期: {date_str}'
            
            # 返回创建的数据
            response_data = {
                'success': True,
                'action': action,
                'message': message,
                'data': {
                    'code': product_code.code,
                    'date': date_str,
                    'production_quantity': float(production_quantity),
                    'sales_quantity': float(sales_quantity),
                    'unit_price': float(unit_price) if unit_price else 0,
                    'unit_cost': float(unit_cost) if unit_cost else 0,
                    'unit_cost2': float(unit_cost2) if unit_cost2 else 0,
                    'total_sales_amount': float(monthly_record.total_sales_amount),
                    'total_cost_amount': float(monthly_record.total_cost_amount),
                    'profit': float(monthly_record.profit)
                }
            }
        
        return JsonResponse(response_data)
        
    except Exception as e:
        return JsonResponse({
            'success': False, 
            'error': f'服务器错误: {str(e)}'
        }, status=500)


# 查询视图函数
@require_http_methods(["GET"])
def get_monthly_record(request):
    """
    查询月度记录
    必须同时指定code和date参数
    """
    try:
        code_str = request.GET.get('code')
        date_str = request.GET.get('date')
        
        if not code_str or not date_str:
            return JsonResponse({
                'success': False, 
                'error': '缺少查询参数: 必须同时指定 code 和 date'
            }, status=400)
        
        # 验证日期格式
        try:
            year = int(date_str[:4])
            month = int(date_str[4:6])
            if month < 1 or month > 12:
                raise ValueError("月份必须在1-12之间")
            date_obj = datetime(year, month, 1).date()
        except (ValueError, IndexError):
            return JsonResponse({
                'success': False, 
                'error': '日期格式错误，请使用yyyymm格式，如202201'
            }, status=400)
        
        # 查询产品代码
        try:
            product_code = ProductCode.objects.get(code=code_str)
        except ProductCode.DoesNotExist:
            return JsonResponse({
                'success': False, 
                'error': f'产品代码 {code_str} 不存在'
            }, status=404)
        
        # 同时使用code和date作为查询条件
        try:
            monthly_record = MonthlyRecord.objects.get(
                code=product_code,
                month=date_obj
            )
            
            data = {
                'code': monthly_record.code.code,
                'date': date_str,
                'production_quantity': float(monthly_record.production_quantity),
                'sales_quantity': float(monthly_record.sales_quantity),
                'unit_price': float(monthly_record.price.unit_price) if monthly_record.price else 0,
                'unit_cost': float(monthly_record.cost.unit_cost) if monthly_record.cost else 0,
                'unit_cost2': float(monthly_record.cost.unit_cost2) if monthly_record.cost else 0,
                'total_sales_amount': float(monthly_record.total_sales_amount),
                'total_cost_amount': float(monthly_record.total_cost_amount),
                'profit': float(monthly_record.profit)
            }
            
            return JsonResponse({
                'success': True,
                'message': '查询成功',
                'data': data
            })
            
        except MonthlyRecord.DoesNotExist:
            return JsonResponse({
                'success': False, 
                'error': f'未找到产品代码 {code_str} 在 {date_str} 的记录'
            }, status=404)
            
    except Exception as e:
        return JsonResponse({
            'success': False, 
            'error': f'查询错误: {str(e)}'
        }, status=500)


# 批量查询视图函数
@require_http_methods(["GET"])
def list_monthly_records(request):
    """
    批量查询月度记录
    可以只指定code查询该产品所有记录，或只指定date查询该月所有产品记录
    """
    try:
        code_str = request.GET.get('code')
        date_str = request.GET.get('date')
        
        if not code_str and not date_str:
            return JsonResponse({
                'success': False, 
                'error': '至少需要指定 code 或 date 参数'
            }, status=400)
        
        # 构建查询条件
        filters = {}
        
        if code_str:
            try:
                product_code = ProductCode.objects.get(code=code_str)
                filters['code'] = product_code
            except ProductCode.DoesNotExist:
                return JsonResponse({
                    'success': False, 
                    'error': f'产品代码 {code_str} 不存在'
                }, status=404)
        
        if date_str:
            try:
                year = int(date_str[:4])
                month = int(date_str[4:6])
                if month < 1 or month > 12:
                    raise ValueError("月份必须在1-12之间")
                date_obj = datetime(year, month, 1).date()
                filters['month'] = date_obj
            except (ValueError, IndexError):
                return JsonResponse({
                    'success': False, 
                    'error': '日期格式错误，请使用yyyymm格式，如202201'
                }, status=400)
        
        # 查询记录
        monthly_records = MonthlyRecord.objects.filter(**filters).select_related('code', 'price', 'cost')
        
        if not monthly_records.exists():
            return JsonResponse({
                'success': True,
                'message': '未找到匹配的记录',
                'data': []
            })
        
        # 构建返回数据
        records_data = []
        for record in monthly_records:
            records_data.append({
                'code': record.code.code,
                'date': record.month.strftime('%Y%m'),
                'production_quantity': float(record.production_quantity),
                'sales_quantity': float(record.sales_quantity),
                'unit_price': float(record.price.unit_price) if record.price else 0,
                'unit_cost': float(record.cost.unit_cost) if record.cost else 0,
                'unit_cost2': float(record.cost.unit_cost2) if record.cost else 0,
                'total_sales_amount': float(record.total_sales_amount),
                'total_cost_amount': float(record.total_cost_amount),
                'profit': float(record.profit)
            })
        
        return JsonResponse({
            'success': True,
            'message': f'查询到 {len(records_data)} 条记录',
            'data': records_data
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False, 
            'error': f'查询错误: {str(e)}'
        }, status=500)

# 20250908添加

from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_http_methods
from django.utils.decorators import method_decorator
from datetime import datetime
from .models import ProductCode, Price, Cost, MonthlyRecord
import pandas as pd
from io import BytesIO
import logging

logger = logging.getLogger(__name__)

@require_http_methods(["GET"])
def export_monthly_records_excel(request):
    """
    根据产品代码和日期范围导出Excel文件
    Excel包含3个sheet: cost, price, cost2
    """
    try:
        # 获取查询参数
        code_str = request.GET.get('code')
        start_date_str = request.GET.get('start_date')
        end_date_str = request.GET.get('end_date')
        
        # 验证必需参数
        if not code_str:
            return JsonResponse({
                'success': False, 
                'error': '缺少必需参数: code'
            }, status=400)
        
        if not start_date_str or not end_date_str:
            return JsonResponse({
                'success': False, 
                'error': '缺少必需参数: start_date 和 end_date'
            }, status=400)
        
        # 验证产品代码
        try:
            product_code = ProductCode.objects.get(code=code_str)
        except ProductCode.DoesNotExist:
            return JsonResponse({
                'success': False, 
                'error': f'产品代码 {code_str} 不存在'
            }, status=404)
        
        # 验证日期格式
        try:
            start_year = int(start_date_str[:4])
            start_month = int(start_date_str[4:6])
            start_date = datetime(start_year, start_month, 1).date()
            
            end_year = int(end_date_str[:4])
            end_month = int(end_date_str[4:6])
            end_date = datetime(end_year, end_month, 1).date()
            
            if start_date > end_date:
                raise ValueError("开始日期不能晚于结束日期")
                
        except (ValueError, IndexError) as e:
            return JsonResponse({
                'success': False, 
                'error': f'日期格式错误，请使用yyyymm格式，如202201。错误: {str(e)}'
            }, status=400)
        
        # 查询数据
        # 查询价格数据
        prices = Price.objects.filter(
            code=product_code,
            month__range=[start_date, end_date]
        ).order_by('month')
        
        # 查询成本数据
        costs = Cost.objects.filter(
            code=product_code,
            month__range=[start_date, end_date]
        ).order_by('month')
        
        # 查询月度记录数据
        monthly_records = MonthlyRecord.objects.filter(
            code=product_code,
            month__range=[start_date, end_date]
        ).select_related('price', 'cost').order_by('month')
        
        if not prices.exists() and not costs.exists() and not monthly_records.exists():
            return JsonResponse({
                'success': False, 
                'error': f'在指定日期范围内未找到产品 {code_str} 的数据'
            }, status=404)
        
        # 创建Excel文件
        output = BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            # Sheet 1: Price数据
            if prices.exists():
                price_data = []
                for price in prices:
                    price_data.append({
                        '年月': price.month.strftime('%Y-%m'),
                        '产品代码': price.code.code,
                        '产品名称': price.code.name,
                        '单价': float(price.unit_price) if price.unit_price else 0
                    })
                
                price_df = pd.DataFrame(price_data)
                price_df.to_excel(writer, sheet_name='price', index=False)
            else:
                # 如果没有数据，创建空的sheet
                pd.DataFrame([{
                    '年月': '无数据',
                    '产品代码': '',
                    '产品名称': '',
                    '单价': 0
                }]).to_excel(writer, sheet_name='price', index=False)
            
            # Sheet 2: Cost数据
            if costs.exists():
                cost_data = []
                for cost in costs:
                    cost_data.append({
                        '年月': cost.month.strftime('%Y-%m'),
                        '产品代码': cost.code.code,
                        '产品名称': cost.code.name,
                        '成本1': float(cost.unit_cost) if cost.unit_cost else 0,
                        '成本2': float(cost.unit_cost2) if cost.unit_cost2 else 0,
                        '总成本': float(cost.unit_cost + cost.unit_cost2) if cost.unit_cost and cost.unit_cost2 else 0
                    })
                
                cost_df = pd.DataFrame(cost_data)
                cost_df.to_excel(writer, sheet_name='cost', index=False)
            else:
                # 如果没有数据，创建空的sheet
                pd.DataFrame([{
                    '年月': '无数据',
                    '产品代码': '',
                    '产品名称': '',
                    '成本1': 0,
                    '成本2': 0,
                    '总成本': 0
                }]).to_excel(writer, sheet_name='cost', index=False)
            
            # Sheet 3: Cost2数据和其他详细信息
            if monthly_records.exists():
                cost2_data = []
                for record in monthly_records:
                    cost2_data.append({
                        '年月': record.month.strftime('%Y-%m'),
                        '产品代码': record.code.code,
                        '产品名称': record.code.name,
                        '生产量': float(record.production_quantity) if record.production_quantity else 0,
                        '销售量': float(record.sales_quantity) if record.sales_quantity else 0,
                        '单价': float(record.price.unit_price) if record.price and record.price.unit_price else 0,
                        '成本1': float(record.cost.unit_cost) if record.cost and record.cost.unit_cost else 0,
                        '成本2': float(record.cost.unit_cost2) if record.cost and record.cost.unit_cost2 else 0,
                        '销售总额': float(record.total_sales_amount),
                        '成本总额': float(record.total_cost_amount),
                        '利润': float(record.profit)
                    })
                
                cost2_df = pd.DataFrame(cost2_data)
                cost2_df.to_excel(writer, sheet_name='cost2', index=False)
            else:
                # 如果没有数据，创建空的sheet
                pd.DataFrame([{
                    '年月': '无数据',
                    '产品代码': '',
                    '产品名称': '',
                    '生产量': 0,
                    '销售量': 0,
                    '单价': 0,
                    '成本1': 0,
                    '成本2': 0,
                    '销售总额': 0,
                    '成本总额': 0,
                    '利润': 0
                }]).to_excel(writer, sheet_name='cost2', index=False)
        
        # 准备响应
        output.seek(0)
        filename = f"{code_str}_{start_date_str}_to_{end_date_str}.xlsx"
        
        response = HttpResponse(
            output.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        
        return response
        
    except ProductCode.DoesNotExist:
        return JsonResponse({
            'success': False, 
            'error': f'产品代码 {code_str} 不存在'
        }, status=404)
    except Exception as e:
        logger.error(f"导出Excel文件时发生错误: {str(e)}")
        return JsonResponse({
            'success': False, 
            'error': f'服务器错误: {str(e)}'
        }, status=500)


# 另一个版本：返回更详细的Excel报告
@require_http_methods(["GET"])
def export_detailed_monthly_report(request):
    """
    导出详细的月度报告Excel文件
    包含更全面的数据分析
    """
    try:
        # 获取查询参数
        code_str = request.GET.get('code')
        start_date_str = request.GET.get('start_date')
        end_date_str = request.GET.get('end_date')
        
        # 验证必需参数
        if not code_str or not start_date_str or not end_date_str:
            return JsonResponse({
                'success': False, 
                'error': '缺少必需参数: code, start_date, end_date'
            }, status=400)
        
        # 验证产品代码
        try:
            product_code = ProductCode.objects.get(code=code_str)
        except ProductCode.DoesNotExist:
            return JsonResponse({
                'success': False, 
                'error': f'产品代码 {code_str} 不存在'
            }, status=404)
        
        # 验证日期格式
        try:
            start_year = int(start_date_str[:4])
            start_month = int(start_date_str[4:6])
            start_date = datetime(start_year, start_month, 1).date()
            
            end_year = int(end_date_str[:4])
            end_month = int(end_date_str[4:6])
            end_date = datetime(end_year, end_month, 1).date()
            
            if start_date > end_date:
                raise ValueError("开始日期不能晚于结束日期")
                
        except (ValueError, IndexError) as e:
            return JsonResponse({
                'success': False, 
                'error': f'日期格式错误，请使用yyyymm格式，如202201。错误: {str(e)}'
            }, status=400)
        
        # 查询所有相关数据
        prices = Price.objects.filter(
            code=product_code,
            month__range=[start_date, end_date]
        ).order_by('month')
        
        costs = Cost.objects.filter(
            code=product_code,
            month__range=[start_date, end_date]
        ).order_by('month')
        
        monthly_records = MonthlyRecord.objects.filter(
            code=product_code,
            month__range=[start_date, end_date]
        ).select_related('price', 'cost').order_by('month')
        
        # 创建Excel文件
        output = BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            # Sheet 1: Summary汇总信息
            summary_data = []
            total_production = 0
            total_sales = 0
            total_sales_amount = 0
            total_cost_amount = 0
            
            for record in monthly_records:
                summary_data.append({
                    '年月': record.month.strftime('%Y-%m'),
                    '生产量': float(record.production_quantity),
                    '销售量': float(record.sales_quantity),
                    '单价': float(record.price.unit_price) if record.price else 0,
                    '单位成本': float(record.cost.unit_cost + record.cost.unit_cost2) if record.cost else 0,
                    '销售总额': float(record.total_sales_amount),
                    '成本总额': float(record.total_cost_amount),
                    '利润': float(record.profit)
                })
                total_production += float(record.production_quantity)
                total_sales += float(record.sales_quantity)
                total_sales_amount += float(record.total_sales_amount)
                total_cost_amount += float(record.total_cost_amount)
            
            if summary_data:
                summary_df = pd.DataFrame(summary_data)
                # 添加总计行
                summary_totals = {
                    '年月': '总计',
                    '生产量': total_production,
                    '销售量': total_sales,
                    '单价': '',
                    '单位成本': '',
                    '销售总额': total_sales_amount,
                    '成本总额': total_cost_amount,
                    '利润': total_sales_amount - total_cost_amount
                }
                summary_df = pd.concat([summary_df, pd.DataFrame([summary_totals])], ignore_index=True)
                summary_df.to_excel(writer, sheet_name='summary', index=False)
            else:
                pd.DataFrame([{'信息': '无数据'}]).to_excel(writer, sheet_name='summary', index=False)
            
            # Sheet 2: Price价格明细
            price_data = []
            for price in prices:
                price_data.append({
                    '年月': price.month.strftime('%Y-%m'),
                    '单价': float(price.unit_price)
                })
            
            if price_data:
                price_df = pd.DataFrame(price_data)
                price_df.to_excel(writer, sheet_name='price', index=False)
            else:
                pd.DataFrame([{'信息': '无价格数据'}]).to_excel(writer, sheet_name='price', index=False)
            
            # Sheet 3: Cost成本明细
            cost_data = []
            for cost in costs:
                cost_data.append({
                    '年月': cost.month.strftime('%Y-%m'),
                    '成本1': float(cost.unit_cost),
                    '成本2': float(cost.unit_cost2),
                    '总成本': float(cost.unit_cost + cost.unit_cost2)
                })
            
            if cost_data:
                cost_df = pd.DataFrame(cost_data)
                cost_df.to_excel(writer, sheet_name='cost', index=False)
            else:
                pd.DataFrame([{'信息': '无成本数据'}]).to_excel(writer, sheet_name='cost', index=False)
        
        # 准备响应
        output.seek(0)
        filename = f"detailed_report_{code_str}_{start_date_str}_to_{end_date_str}.xlsx"
        
        response = HttpResponse(
            output.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        
        return response
        
    except Exception as e:
        logger.error(f"导出详细报告时发生错误: {str(e)}")
        return JsonResponse({
            'success': False, 
            'error': f'服务器错误: {str(e)}'
        }, status=500)